package com.mysafe.provision.service.account;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import com.mysafe.provision.exception.ValidationError;
import com.mysafe.provision.exception.ValidationException;
import com.mysafe.provision.model.account.Account;
import com.mysafe.provision.persistence.account.IAccountDAO;
import com.mysafe.provision.service.PersistenceService;

public class AccountService extends PersistenceService<Account> implements IAccountService, Serializable {

	private static final long serialVersionUID = -8095930497040666506L;

	private IAccountDAO accountDAO;
	
	@Inject
	public AccountService(IAccountDAO accountDAO) {
		super(accountDAO);
		this.accountDAO = accountDAO;
	}
	
	@Override
	public boolean verifyAccess(Account loginAccount) {
		boolean accessGranted = false;
		Account account = null; 
		if (loginAccount != null) {
			account = accountDAO.find(loginAccount.getLogin());
			if (account != null) {
				accessGranted = true;
			}
		}
		return accessGranted;
	}

	@Override
	public void createAccount(Account account) throws ValidationException {
		validateInsert(account);
		accountDAO.persist(account);
	}

	@Override
	public void validateInsert(Account account) throws ValidationException {
		List<ValidationError> errors = new ArrayList<ValidationError>();
		if (account == null) {
			errors.add(new ValidationError(ValidationError.INVALID));
		} else {
			if (account.getLogin() == null || account.getLogin().equals("")) {
				errors.add(new ValidationError(ValidationError.REQUIRED));
			}
		}
		
		if (!errors.isEmpty()) {
			throw new ValidationException(errors);
		}
	}

	@Override
	public void validateUpdate(Account entity) throws ValidationException {
		// TODO Auto-generated method stub
		
	}

}
